﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using TimeTableTool.DTO;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Data.SQLite;
using System.Data.SqlServerCe;

namespace TimeTableTool
{
    public partial class Form1 : Form
    {

        private String stationPath;
        private String timePath;
        private String outputPath;

        public Form1()
        {
            InitializeComponent();
        }

        private void makeDataBaseFile(String pathToStationFile, String pathToTimeTableFile, String outputPath)
        {

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Station>));
            TextReader reader = new StreamReader(pathToStationFile);
            List<Station> stations = (List<Station>)xmlSerializer.Deserialize(reader);


            XmlSerializer deserializer = new XmlSerializer(typeof(List<TransitWithTimes>));
            TextReader textReader = new StreamReader(pathToTimeTableFile);
            List<TransitWithTimes> transitList = (List<TransitWithTimes>)deserializer.Deserialize(textReader);


            Dictionary<String, int> lineList = new Dictionary<string, int>();
            Dictionary<String, Station> stationList = new Dictionary<string, Station>();
            //List<TimeTableDTO> timeTableList = new List<TimeTableDTO>();
            List<ReacheableTableDTO> reacheableList = new List<ReacheableTableDTO>();
            int lineId = 0;
            int stationId = 0;

            foreach (TransitWithTimes transit in transitList)
                foreach (int time in transit.HolidaysHours)
                {
                    if (time == 1475)
                    {
                        int i = 0;
                    }
                }

            foreach (Station station in stations)
            {
                stationList.Add(station.Name, station);

            }

            foreach (TransitWithTimes transit in transitList)
            {

                if (lineList.ContainsKey(transit.Line + "|" + transit.Direction) == false)
                {
                    lineList.Add(transit.Line + "|" + transit.Direction, lineId);
                    lineId++;
                }

            }


            foreach (TransitWithTimes transit in transitList)
            {

                foreach (int time in transit.HolidaysHours)
                {
                    if (time == 1475)
                    {
                        int i = 0;
                    }
                }

                int station_id = stationList[transit.Station].id;
                int line_id = lineList[transit.Line + "|" + transit.Direction];
                foreach (Transit reacheableStations in transit.TransitsFromThisStation)
                {
                    ReacheableTableDTO reachableTable = new ReacheableTableDTO();
                    reachableTable.StartStationId = station_id;
                    reachableTable.LineId = line_id;
                    reachableTable.Distance = reacheableStations.TimeDistance;
                    reachableTable.DestinationStationId = stationList[reacheableStations.DestinationStation].id;

                    ReacheableTableDTO sameStation = reacheableList.Find(x => x.LineId == line_id && x.StartStationId == station_id && x.DestinationStationId == reachableTable.DestinationStationId);
                    if (sameStation == null)
                    {
                        reacheableList.Add(reachableTable);
                    }


                }
            }




            List<TimeTableDTO> timeTableList = new List<TimeTableDTO>();
            foreach (TransitWithTimes transit in transitList)
            {
                foreach (int time in transit.WorkingDaysHours)
                {
                    TimeTableDTO timeTable = new TimeTableDTO();
                    timeTable.DayType = "n";
                    timeTable.StationId = stationList[transit.Station].id;
                    timeTable.Time = time;
                    timeTable.LineId = lineList[transit.Line + "|" + transit.Direction];
                    timeTableList.Add(timeTable);
                }

                foreach (int time in transit.HolidaysHours)
                {
                    TimeTableDTO timeTable = new TimeTableDTO();
                    timeTable.DayType = "h";
                    timeTable.StationId = stationList[transit.Station].id;
                    timeTable.Time = time;
                    timeTable.LineId = lineList[transit.Line + "|" + transit.Direction];
                    timeTableList.Add(timeTable);
                }

                foreach (int time in transit.FreeDaysHours)
                {
                    TimeTableDTO timeTable = new TimeTableDTO();
                    timeTable.DayType = "f";
                    timeTable.StationId = stationList[transit.Station].id;
                    timeTable.Time = time;
                    timeTable.LineId = lineList[transit.Line + "|" + transit.Direction];
                    timeTableList.Add(timeTable);
                }

            }

            //SqlCeConnection connectionCe = DBHelperCE.GetConnection();
            SQLiteConnection connection = DBHelper.GetConnection(outputPath);

            LineDao lineDao = new LineDao(connection);
            StationDao stationDao = new StationDao(connection);
            TimeTableDao timeTableDao = new TimeTableDao(connection);
            ReacheableTableDao reacheableTableDao = new ReacheableTableDao(connection);

            reacheableTableDao.BulkInsert(reacheableList);

            SQLiteTransaction transaction = connection.BeginTransaction();
            foreach (KeyValuePair<string, int> pair in lineList)
            {
                lineDao.insertLine(pair.Value, pair.Key);
            }
            foreach (KeyValuePair<string, Station> pair in stationList)
            {
                stationDao.insertStation(pair.Value);
            }

            timeTableDao.BulkInsert(timeTableList);

            transaction.Commit();


        }


        private void parseDPMKFiles()
        {

            DirectoryInfo di = new DirectoryInfo("data");
            FileInfo[] rgFiles = di.GetFiles("*.txt");

            List<TransitWithTimes> parsedTransits = new List<TransitWithTimes>();
            foreach (FileInfo fileInfo in rgFiles)
            {
                StreamReader streamReader = new StreamReader(fileInfo.FullName);
                string source = streamReader.ReadToEnd();
                streamReader.Close();
                HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                htmlDoc.OptionFixNestedTags = true;
                htmlDoc.LoadHtml(source);

                parsedTransits.AddRange(ParseExactLine(htmlDoc));
            }

            XmlSerializer serializer = new XmlSerializer(typeof(List<TransitWithTimes>));
            TextWriter textWriter = new StreamWriter(@"parsedData.xml");
            serializer.Serialize(textWriter, parsedTransits);
            textWriter.Close();
        }


        private double distance(double lat1, double lon1, double lat2, double lon2, char unit)
        {
            double theta = lon1 - lon2;
            double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) +
                          Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) *
                          Math.Cos(deg2rad(theta));
            dist = Math.Acos(dist);
            dist = rad2deg(dist);
            dist = dist * 60 * 1.1515;

            //v kilometroch
            dist = dist * 1.609344;
            return (dist);
        }

        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //::  This function converts decimal degrees to radians             :::
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        private double deg2rad(double deg)
        {
            return (deg * Math.PI / 180.0);
        }

        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        //::  This function converts radians to decimal degrees             :::
        //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        private double rad2deg(double rad)
        {
            return (rad / Math.PI * 180.0);
        }



        /*
        private void ExploreStopsLink(HtmlAgilityPack.HtmlDocument htmlDoc )
        {
            WebClient client = new WebClient();
            List<StopToExplore> stopsToExplore = ParseDirectionLine(htmlDoc);

            foreach (StopToExplore stop in stopsToExplore)
            {
                String sourceTable = client.DownloadString("http://www.imhd.zoznam.sk/ke/"+stop.link);
                HtmlAgilityPack.HtmlDocument tableDoc = new HtmlAgilityPack.HtmlDocument();
                tableDoc.OptionFixNestedTags = true;
                tableDoc.LoadHtml(sourceTable);

                //ParseExactLine(tableDoc);
            }
        }
         * 
         */

        /*
        struct StopToExplore
        {
            public String stationName {get;set;}
            public String link { get; set; }
            public String direction { get; set; }
        }

        struct LineToExplore
        {
            public String lineName { get; set; }
            public String postLink { get; set; }
            public String postValues { get; set; }
            public String lineType { get; set; }
        }
        */

        /*
        private List<LineToExplore> ParseLines(HtmlAgilityPack.HtmlDocument htmlDoc)
        {
            HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr[1]/td/select/option");
            List<LineToExplore> lines = new List<LineToExplore>();
            for (int lineType = 1; lineType < 4; lineType++)
            {
                for (int i = 1; i < nodes.Count; i++)
                {
                    LineToExplore line = new LineToExplore();
                    HtmlNode postLinkNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr["+lineType.ToString()+"]/td/form");
                    line.postLink = postLinkNode.Attributes["action"].Value;
                    line.postValues = nodes[i].Attributes["value"].Value;
                    line.lineName = line.postValues.Replace("&d=", "");
                    lines.Add(line);

                }
            }


            return lines;
        }

        private List<StopToExplore> ParseDirectionLine(HtmlAgilityPack.HtmlDocument htmlDoc)
        {
            List<StopToExplore> stops = new List<StopToExplore>();

            String[] directions = new String[2];
                                        
            HtmlNode node = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td/table/tr/th");
                        
            if (node!=null)
                directions[0] = node.InnerText.Replace("Smer: ", ""); ;

            node = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[3]/table/tr/th");
            if (node != null)
                directions[1] = node.InnerText.Replace("Smer: ","");

            for (int i = 0; i < 2;i++ )
            {
                if (directions[0] != null)
                {
                    HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td["+ ((i==0)? "1" : "3") +"]/table/tr");
                    for (int j = 3; j <4; j++)
                    {
                        StopToExplore stopToExplore = new StopToExplore();
                        HtmlNode textNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[" + ((i == 0) ? "1" : "3") + "]/table/tr[" + j.ToString() + "]/td[1]//a");
                        stopToExplore.stationName = textNode.InnerText.Replace("&nbsp;", "");
                        //HtmlNode nodee = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[" + ((i == 0) ? "1" : "3") + "]/table/tr[" + j.ToString() + "]/td[1]//a");
                        stopToExplore.link = textNode.Attributes["href"].Value;
                        stopToExplore.direction = directions[i];
                        stops.Add(stopToExplore);
                    }
                }
            }

            return stops;

        }

        */




        private List<TransitWithTimes> ParseExactLine(HtmlAgilityPack.HtmlDocument htmlDoc)
        {
            if (htmlDoc.DocumentNode != null)
            {
                HtmlNode nameNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td/table/tr/td/p/span/font[2]");
                String lineName = nameNode.InnerText;
                if (lineName == "34")
                {
                    int stop = 1;
                }
                HtmlNode directionNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[2]/table/tr/td/font[4]");
                String direction = directionNode.InnerText;

                HtmlNode startStationNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[2]/table/tr/td/font[2]");
                String startStation = startStationNode.InnerText;

                List<Transit> transitList = new List<Transit>();
                HtmlNodeCollection distanceNodes = htmlDoc.DocumentNode.SelectNodes("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[1]/table/tr");

                //find the select station with >>
                int currentStationIndex = 4;
                HtmlNodeCollection distanceNodesForEvaluate = htmlDoc.DocumentNode.SelectNodes("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[1]/table/tr");
                for (int position = 2; position < distanceNodesForEvaluate.Count - 1; position++)
                {
                    if (distanceNodesForEvaluate[position].NextSibling.InnerText.StartsWith("»&nbsp;&nbsp;"))
                    {
                        currentStationIndex = position;
                        position = distanceNodes.Count;
                    }

                }

                Regex regex = new Regex("[0-9]+");
                if (distanceNodes != null)
                {
                    for (int i = currentStationIndex + 1; i < distanceNodesForEvaluate.Count - 1; i++)
                    {
                        Transit timeTable = new Transit();
                        HtmlNode valueNode = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[1]/table/tr[" + (i + 2).ToString() + "]/td[1]/p");

                        if (valueNode != null)
                        {
                            //String value = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[1]/table/tr[" + (i + 2).ToString() + "]/td[1]/p").NextSibling.InnerText;
                            int distance = int.Parse(regex.Matches(valueNode.NextSibling.InnerText)[0].ToString());
                            String destination;
                            if (i == distanceNodes.Count - 1)
                            {
                                destination = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td/table/tr[" + i.ToString() + "]/td[3]/font/b").InnerText;
                            }
                            else
                            {
                                destination = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[1]/table/tr[" + (i + 2).ToString() + "]/td[3]").InnerText;
                            }

                            destination = destination.Replace("&nbsp;", " ");
                            timeTable.DestinationStation = destination.Trim();
                            timeTable.TimeDistance = distance;
                            transitList.Add(timeTable);
                        }

                    }
                }

                List<int> workingTimes = extractTimes(htmlDoc, 1);
                List<int> workingTimesHoliday = extractTimes(htmlDoc, 2);
                List<int> freeTimes = extractTimes(htmlDoc, 3);

                List<TransitWithTimes> transitsWithTimes = new List<TransitWithTimes>();

                TransitWithTimes firstTransit = new TransitWithTimes();
                firstTransit.Direction = direction;
                firstTransit.FreeDaysHours = freeTimes;
                firstTransit.HolidaysHours = workingTimesHoliday;
                firstTransit.WorkingDaysHours = workingTimes;
                firstTransit.Station = startStation;
                firstTransit.TransitsFromThisStation = transitList;
                firstTransit.Line = lineName;
                transitsWithTimes.Add(firstTransit);

                foreach (Transit transit in transitList)
                {
                    //for each hop A->x, create next hops
                    int index = transitList.FindIndex(x => x.DestinationStation == transit.DestinationStation) + 1;
                    transitsWithTimes.Add(RecalculateTimeTable(transit.DestinationStation, lineName, direction, index, transitList, transit.TimeDistance, workingTimes, workingTimesHoliday, freeTimes));

                }

                return transitsWithTimes;

            }
            return null;

        }

        public struct TransitWithTimes
        {
            public String Line { get; set; }
            public String Station { get; set; }
            public String Direction { get; set; }
            public List<Transit> TransitsFromThisStation { get; set; }
            public List<int> WorkingDaysHours { get; set; }
            public List<int> HolidaysHours { get; set; }
            public List<int> FreeDaysHours { get; set; }
        }

        private TransitWithTimes RecalculateTimeTable(String starStationName, String line, String direction, int startIndex, List<Transit> reacheableStations, int timeDistance, List<int> working, List<int> holiday, List<int> free)
        {
            TransitWithTimes transitWithTimes = new TransitWithTimes();
            List<Transit> nextTransits = new List<Transit>();
            for (int i = startIndex; i < reacheableStations.Count; i++)
            {
                Transit transit = new Transit();
                //transit.startStation = starStationName;
                transit.TimeDistance = reacheableStations[i].TimeDistance - timeDistance;
                transit.DestinationStation = reacheableStations[i].DestinationStation;

                nextTransits.Add(transit);
            }

            List<int> workingDays = new List<int>();
            for (int i = 0; i < working.Count; i++)
            {

                workingDays.Add(AddTime(working[i], timeDistance));
            }

            List<int> holidayDays = new List<int>();
            for (int i = 0; i < holiday.Count; i++)
            {
                int test = AddTime(holiday[i], timeDistance);
                holidayDays.Add(AddTime(holiday[i], timeDistance));
            }

            List<int> freeDays = new List<int>();
            for (int i = 0; i < free.Count; i++)
            {
                int test = AddTime(free[i], timeDistance);
                freeDays.Add(AddTime(free[i], timeDistance));
            }

            transitWithTimes.TransitsFromThisStation = nextTransits;
            transitWithTimes.Station = starStationName;
            transitWithTimes.WorkingDaysHours = workingDays;
            transitWithTimes.FreeDaysHours = freeDays;
            transitWithTimes.HolidaysHours = holidayDays;
            transitWithTimes.Line = line;
            transitWithTimes.Direction = direction;



            return transitWithTimes;
        }

        public static int AddTime(int currentTime, int minutesToAdd)
        {
            int tempTime = currentTime;
            int hours = (currentTime % 100 + minutesToAdd) / 60;
            currentTime += hours * 100;
            currentTime += minutesToAdd - (hours * 60);
            if (currentTime / 2359 >= 1)
            {
                currentTime = currentTime - (2359 * (currentTime / 2359));
            }

            return currentTime;
        }

        private List<int> extractTimes(HtmlAgilityPack.HtmlDocument htmlDoc, int column)
        {
            List<int> times = new List<int>();
            HtmlNodeCollection workingDays = htmlDoc.DocumentNode.SelectNodes("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[2]/table/tr[2]/td/table/tr[2]/td[" + column.ToString() + "]/table/tr");
            Regex regex = new Regex("[0-9]+");
            if (workingDays != null)
            {
                for (int i = 2; i < workingDays.Count + 1; i++)
                {
                    int time = -1;
                    String hour = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[2]/table/tr[2]/td/table/tr[2]/td[" + column.ToString() + "]/table/tr[" + i.ToString() + "]/td/b/font").InnerText;
                    time = int.Parse(hour) * 100;
                    //String destination = htmlDoc.DocumentNode.SelectSingleNode("/html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td/table/tr[" + i.ToString() + "]/td[3]/font/a/span").InnerText;
                    ///html/body/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/font
                    String minutes = htmlDoc.DocumentNode.SelectSingleNode("html/body/table/tr[2]/td/table/tr/td[2]/table/tr/td[2]/table/tr[2]/td/table/tr[2]/td[" + column.ToString() + "]/table/tr[" + i.ToString() + "]/td[2]/font").InnerText;
                    foreach (Match match in regex.Matches(minutes))
                    {
                        int minute = int.Parse(match.ToString());
                        //times.Add(time + minute);
                        int tempTime = AddTime(time, minute);
                        times.Add(AddTime(time, minute));
                    }
                }
            }
            return times;
        }


        private List<Line> ExtractLineData(XmlDocument doc)
        {
            List<Line> lines = new List<Line>();
            XmlNodeList elemList = doc.SelectNodes("/data/spoje/line");
            for (int i = 0; i < elemList.Count; i++)
            {
                Line line = new Line();
                line.name = elemList[i].Attributes["name"].Value;
                line.direction = elemList[i].Attributes["direction"].Value;
                line.type = elemList[i].Attributes["type"].Value;
                line.timeUrl = elemList[i].Attributes["timeLink"].Value;
                lines.Add(line);
            }
            return lines;
        }

        private List<Station> ExtractAllStations(XmlDocument doc)
        {

            XmlNodeList elemList = doc.SelectNodes("/data/stanice/station");
            List<Station> stations = new List<Station>();
            for (int i = 0; i < elemList.Count; i++)
            {
                Station station = new Station();
                station.Name = elemList[i].Attributes["name"].Value;
                station.id = i;
                stations.Add(station);
            }

            return stations;
        }

        private List<Station> ExtractAllStaions()
        {
            String topHtmlEnd = "Vyber zast&#x00e1;vku:</b></p><p>";
            WebClient client = new WebClient();
            String source = client.DownloadString("http://imhd.zoznam.sk/ke/wap.php?www=*cepo,wapzastavka");
            //remove top unnecessary source
            //source = source.Substring(source.IndexOf(topHtmlEnd) + topHtmlEnd.Length);
            //remove botton
            //"index=\\d*"
            String nextPage = "<br/></p><p align=\"center\">";
            int position = source.IndexOf(nextPage) + nextPage.Length;
            String sourceNextPage = source.Substring(position, source.Length - position);
            //source = source.Remove(source.IndexOf(nextPage));

            List<Station> stations = new List<Station>();
            String idPosition = ";k=";
            int lengthPosition = idPosition.Length;
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ProhibitDtd = false;
            using (XmlReader reader = XmlReader.Create(new StringReader(source), settings))
            {

                while (reader.Read())
                {
                    // Only detect start elements.
                    if (reader.IsStartElement())
                    {
                        // Get element name and switch on it.
                        switch (reader.Name)
                        {
                            case "a":
                                // Detect this article element.
                                Console.WriteLine("Start <article> element.");
                                // Search for the attribute name on this current node.
                                string attribute = reader["href"];
                                if (attribute != null)
                                {
                                    // "http://imhd.zoznam.sk/ke/wap.php?www=*cepo,wapzastavka&amp;k=700"
                                    int index = attribute.LastIndexOf("&k=");
                                    int id = int.Parse(attribute.Substring(index + lengthPosition, attribute.Length - (index + lengthPosition)));

                                }
                                // Next read will contain text.
                                if (reader.Read())
                                {
                                    String name = reader.Value.Trim();
                                }
                                break;
                        }
                    }
                }
            }
            return stations;
        }

        private void stationPathBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            DialogResult result = fileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                stationPath = fileDialog.FileName;
                stationFileTxt.Text = fileDialog.FileName;
                enableIfAllSet();
            }
        }

        private void timetablePathBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            DialogResult result = fileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                timePath = fileDialog.FileName;
                timeTableFileTxt.Text = fileDialog.FileName;
                enableIfAllSet();
            }
        }

        private void savePathBtn_Click(object sender, EventArgs e)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.FileName = "database.db";
            DialogResult result = fileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                outputPath = fileDialog.FileName;
                outputTxt.Text = fileDialog.FileName;
                enableIfAllSet();
            }
        }

        private void createDbBtn_Click(object sender, EventArgs e)
        {
            createDbBtn.Enabled = false;
            progressBar1.Visible = true;
            backgroundWorker1.RunWorkerAsync();
        }

        bool wasError = false;
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                makeDataBaseFile(stationPath, timePath, outputPath);
            }
            catch (Exception exc)
            {
                wasError = true;
            }
        }

        private void showEror()
        {
            MethodInvoker method = delegate
            {
                MessageBox.Show("Došlo k chybe pri spracovaní", "Chyba", MessageBoxButtons.OK, MessageBoxIcon.Error);
            };

            if (InvokeRequired)
                BeginInvoke(method);
            else
                method.Invoke();
        }

        private void enableIfAllSet()
        {
            createDbBtn.Enabled = (stationPath != null && timePath != null && outputPath != null);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (wasError)
            {
                showEror();
                wasError = false;
            }
            else
            {
                MessageBox.Show("Súbor s dátami bol úspešne vytvorený");
            }
            progressBar1.Visible = false;
            createDbBtn.Enabled = true;
        }
    }
}
